# 登录 & 令牌生成
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends
from models.user import User
from core.security import verify_password, create_access_token
from datetime import timedelta


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/login")


async def authenticate_user(username: str, password: str):
    user = await User.get_or_none(username=username)
    if user and verify_password(password, user.hashed_password):
        return user
    return None


def create_token_response(username: str):
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(
        data={"sub": username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}